package pe.com.bn.sach.dao.impl;


import pe.com.bn.sach.dao.ReniecDAO;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor;

import org.springframework.jdbc.LobRetrievalFailureException;
import org.springframework.dao.EmptyResultDataAccessException;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

import java.sql.ResultSet;
import org.springframework.util.FileCopyUtils;
 
public class ReniecImpl extends JdbcDaoSupport implements ReniecDAO{
	protected final Log logger = LogFactory.getLog(getClass());

private LobHandler lobHandler;

	public void setLobHandler(LobHandler lobHandler) {
	this.lobHandler = lobHandler;
}

	
	public void streamImage(final String dni, final OutputStream contentStream) throws Exception {
		
		
		
		
		getJdbcTemplate().query( 
				" SELECT f12_foto FROM BN_SGHB.BNHBF12_FOTO WHERE f12_num_doc ='"+dni+"'",
				new AbstractLobStreamingResultSetExtractor() {
					protected void handleNoRowFound() throws LobRetrievalFailureException {
						
						throw new EmptyResultDataAccessException(
						    "foto con el nombre '" + dni + "' no encontrado en la BD", 1);
					}
					public void streamData(ResultSet rs) throws SQLException, IOException {
						InputStream is = lobHandler.getBlobAsBinaryStream(rs, 1);
						if (is != null) {
							FileCopyUtils.copy(is, contentStream);
							
						}
					}
				}
		);
	}
	
	public void streamImageFirma(final String dni, final OutputStream contentStream) throws Exception {
		getJdbcTemplate().query(
				" SELECT f11_firma FROM BN_SGHB.BNHBF11_FIRMA WHERE f11_num_doc ='"+dni+"'",
				new AbstractLobStreamingResultSetExtractor() {
					protected void handleNoRowFound() throws LobRetrievalFailureException {
						
						throw new EmptyResultDataAccessException(
						    "Firma con el nombre '" + dni + "' no encontrado en la BD", 1);
					}
					public void streamData(ResultSet rs) throws SQLException, IOException {
						InputStream is = lobHandler.getBlobAsBinaryStream(rs, 1);
						byte b[] = lobHandler.getBlobAsBytes(rs, 1);
						
						if (is != null) {
							
							FileCopyUtils.copy(is, contentStream);
							
						}
					}
				}
		);
		
	}
	

	
	
	
	
	

	

	
}
